<template>
	<div class="login-container">
    <h1 class="project-title">{{ projectTitle }}</h1>
    <div class="main">  	
		  <!-- <input @change="test" type="checkbox" ref="checkbox" id="chk" aria-hidden="true"> -->
			<input type="checkbox" ref="checkbox" id="chk" aria-hidden="true">
			  <div class="signup">
          <el-form class="login-form" ref="loginDom" :model="loginForm" :rules="rules">
					  <label for="chk" aria-hidden="true">登录</label>
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" type="text" placeholder="用户名" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input 
								type="password" 
								show-password 
								v-model="loginForm.password" 
								placeholder="密码" 
							/>
            </el-form-item>
					  <button type="button" @click.enter="handleLogin">登录</button>
        </el-form>
			  </div>
      
			  <div class="login">
					<el-form class="login-form" ref="signupDom" :model="signupForm" :rules="rules">
					  <label for="chk" aria-hidden="true">注册</label>
            <el-form-item prop="userName">
              <el-input v-model="signupForm.userName" type="text" placeholder="用户名" />
            </el-form-item>
						<el-form-item prop="nickName">
              <el-input v-model="signupForm.nickName" type="text" placeholder="昵称" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="signupForm.password" type="password" name="pswd" placeholder="密码" show-password />
            </el-form-item>
            <el-form-item prop="repeatPassword">
              <el-input v-model="signupForm.repeatPassword" type="password" placeholder="确认密码" show-password />
            </el-form-item>
					  <button type="button" @click="handleRegister">注册</button>
          </el-form>
          
			  </div>
	  </div>
  </div>
  
</template>
<script setup>
import { ref, watch, onMounted, onUnmounted, onActivated } from 'vue';
import { register } from '@/api/user';
import { global } from '@/utils/status';
import { useRouter, useRoute } from 'vue-router';
import useUserStore from '@/stores/user'
import * as rule from '@/utils/rules'
import { ElMessage } from 'element-plus';

const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const defaultSignup = {
	userName: '',
	nickName: '',
  password: '',
  repeatPassword: ''
}
const checkbox = ref(null);
// 注册表单DOM
const signupDom = ref(null);
// 登录表单对象
const loginForm = ref({
	flag: false,
  username: '',
  password: ''
});
// 注册表单对象
const signupForm = ref({
	flag: false,
	userName: '',
	nickName: '',
  password: '',
  repeatPassword: ''
});
// 登录表单DOM
const loginDom = ref(null);
// 验证规则
const rules = {
	username: rule.userName,
	userName: rule.userName,
	nickName: rule.userName,
	password: rule.password,
	repeatPassword: [{ required: true, validator(rule, value, callback){
		if (!value){
			callback(new Error('请再次输入密码'));
		} else if (value != signupForm.value.password){
			callback(new Error('两次密码输入不一致，请核对'));
		} else {
			callback();
		}
	}}]
};
// 路由重定向参数
const redirect = ref(undefined);
const otherQuery = ref({});
const projectTitle = ref(global.projectTitle);

watch(route, (newRoute) => {
	// const { query } = newRoute.query;
	const { query } = newRoute;
	// console.log(query)
	if (query) {
		redirect.value = query.redirect;
		otherQuery.value = Object.keys(query).reduce((queryObj, key) => {
			if (key !== 'redirect'){
				queryObj[key] = query[key];
			}
			return queryObj;
		}, {});
	}
}, { immediate: true});

// 登录
function handleLogin(){
	// console.log('登录')
	loginDom.value.validate(valid => {
		if (valid){
			loginForm.value.flag = true;
			userStore.login(loginForm.value)
				.then(() => {
					ElMessage.success('登录成功!');
					// console.log(redirect.value)
					router.push({ path: redirect.value || '/', query: otherQuery.value});
				})
				.catch(err => {
					ElMessage.error(err)
				})
				.finally(() => {
					loginForm.value.flag = false;
				})
		} else {
			ElMessage.warning(global.message.validFail);
		}
	})
}
// todo - 这里要完成注册后的流程
function handleRegister(){
	if (signupDom.value.flag){
		ElMessage.warning('当前正在注册，请稍后');
		return;
	}
	signupDom.value.validate(valid => {
		if (valid){
			signupForm.value.flag = true;
			register(signupForm.value)
				.then(res => {
					ElMessage.success('注册成功!');
					if (checkbox.value && checkbox.value.checked) {
						checkbox.value.checked = !checkbox.value.checked;
					}
					signupForm.value = Object.assign(signupForm.value, defaultSignup);
				})
				.catch(err => {
					console.log('注册错误')
					console.log(err)
					// ElMessage.error(err)
				})
				.finally(() => {
					signupForm.value.flag = false;
				})
		} else {
			ElMessage.warning(global.message.validFail);
		}
	})
}
function keydownEnter(e){
	if (e.code == 'Enter' && checkbox.value && !checkbox.value.checked && loginForm.value.flag){
		// console.log('return')
		return;
	}
	if (e.code == 'Enter' && checkbox.value && checkbox.value.checked && signupForm.value.flag){
		return;
	}
	if (e.code == 'Enter' && checkbox.value && !checkbox.value.checked){
		handleLogin();
	} else if (e.code == 'Enter' && checkbox.value && checkbox.value.checked){
		handleRegister();
	}
}


onMounted(() => {
	window.addEventListener('keydown', keydownEnter, false);
});

onUnmounted(() => {
	window.removeEventListener('keydown', keydownEnter, false);
});

// function test(){
// 	console.dir(checkbox.value)
// }

</script>
<style lang='scss' scoped>
.login-container {
	margin: 0;
	padding: 0;
	display: flex;
  flex-direction: column;
	justify-content: center;
	align-items: center;
	min-height: 100vh;
	font-family: 'Jost', sans-serif;
	// background: linear-gradient(to bottom, #0f0c29, #302b63, #24243e);
	background: var(--color-main-linear);
}
.project-title {
  // color: #fff;
	color: var(--color-white-10);
}
.main{
	width: 350px;
	height: 500px;
	overflow: hidden;
	border-radius: 10px;
	box-shadow: 5px 20px 50px var(--color-black-10);
  margin-top: 100px;
}
#chk{
	display: none;
}
.signup{
	position: relative;
	width:100%;
	height: 100%;
}
label{
	color: var(--color-white-10);
	font-size: 2.3em;
	justify-content: center;
	display: flex;
	margin: 50px;
	font-weight: bold;
	cursor: pointer;
	transition: .5s ease-in-out;
}
input{
	width: 60%;
	height: 10px;
	background: var(--color-login-input);
	justify-content: center;
	display: flex;
	margin: 20px auto;
	padding: 12px;
	border: none;
	outline: none;
	border-radius: 5px;
}
button{
	width: 60%;
	height: 40px;
	margin: 10px auto;
	justify-content: center;
	display: block;
	color: var(--color-white-10);
	// background: #573b8a;
	background: var(--color-main);
	font-size: 1em;
	font-weight: bold;
	margin-top: 30px;
	outline: none;
	border: none;
	border-radius: 5px;
	transition: .2s ease-in;
	cursor: pointer;
}
button:hover{
	// background: #6d44b8;
	background: var(--color-main-5);
}
.login{
	height: 460px;
	background: var(--color-login-register);
	border-radius: 60% / 10%;
	transform: translateY(-180px);
	transition: .8s ease-in-out;
}
.login label{
	// color: #573b8a;
	color: var(--color-main);
	transform: scale(.6);
}

#chk:checked ~ .login{
	transform: translateY(-500px);
}
#chk:checked ~ .login label{
	transform: scale(1);	
}
#chk:checked ~ .signup label{
	transform: scale(.6);
}

.el-input {
  width: 60%;
  margin: 0 auto;
  justify-content: center;
	display: flex;
  &::v-deep .el-input__wrapper {
    background-color: var(--color-login-input);
  }
}
@media (min-width: 1500px){
  .main {
    width: 650px;
  }
}
@media (max-width: 1500px){
  .main {
    width: 500px;
  }
}
@media (max-width: 900px){
  .main {
    width: 350px;
  }
}
.el-form-item {
	margin-bottom: 25px;
	&::v-deep .el-form-item__error {
		left: 20%;

	}
}
.login-form::v-deep .el-input__wrapper.is-focus {
	box-shadow: 0 0 0 1px var(--color-main) inset;
}
</style>